package com.coe3.handle;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import com.coe3.data.Information;
import com.coe3.data.PathManager;
import com.daydr3am.thenation.TheNationMain;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;

public class PDFDownloadAsync extends AsyncTask<String, String, String>  {
	
	private Activity mActivity = null;
	private static String mFileName = null;
	private final int URL_IMAGE = 0;
	private final int URL_FILE_PDF = 1;
	
	public PDFDownloadAsync( Activity activity, String fileName) {
		this.mActivity = activity;
		setFileName(fileName);
	}
	
	@Override
    protected void onPreExecute() {
        super.onPreExecute();
//        mStore.showDownload();
        TheNationMain.getInstanceDownloadDialog(mActivity).show();
    }

	@SuppressLint("WorldReadableFiles")
	@Override
    protected String doInBackground( String... aurl ) {
        
		try {
			PathManager.mkdir(mActivity, true);
			DownloadFileImage(aurl[URL_IMAGE]);
			DownloadFilePDF(aurl[URL_FILE_PDF]);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e(Information.TAG_DBUG, e.getMessage());
		}
        
        return null;
        
    }
	
	public void DownloadFilePDF(String strURL) {
		int count;

        try {
            URL url = new URL(strURL);
            URLConnection conexion = url.openConnection();
            conexion.setConnectTimeout(90000);
            conexion.connect();

            int lenghtOfFile = conexion.getContentLength();

            InputStream input = new BufferedInputStream( url.openStream() );
            File file = new File(PathManager.getExternalCacheDir(mActivity, true), getFileName(PathManager.Extension_PDF));
            OutputStream output = new FileOutputStream(file);

            byte data[] = new byte[1024];

            long total = 0;
            
//            mStore.downloadDialog().setMax( lenghtOfFile );
            TheNationMain.getInstanceDownloadDialog(mActivity).setMax( lenghtOfFile );

            while ( ( count = input.read(data) ) != -1 ) {
                total += count;
                publishProgress( "" + total );
                output.write( data, 0, count );
            }

            output.flush();
            output.close();

            input.close();
        } catch (Exception e) {
        	e.printStackTrace();
        	Log.e(Information.TAG_DBUG, e.getMessage());
        }
	}
	
	public void DownloadFileImage(String strURL) {
		try {
            URL url = new URL(strURL); //you can write here any link
            File file = new File(PathManager.getExternalCacheDir(mActivity, true), getFileName(PathManager.Extension_JPG));
            
            long startTime = System.currentTimeMillis();
            Log.d("DownloadManager", "download begining");
            Log.d("DownloadManager", "download url:" + url);
            Log.d("DownloadManager", "downloaded file name:" + file.getAbsolutePath());

            /* Open a connection to that URL. */
            URLConnection ucon = url.openConnection();

            /*
             * Define InputStreams to read from the URLConnection.
             */
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

            /*
             * Read bytes to the Buffer until there is nothing more to read(-1).
             */
            ByteArrayBuffer baf = new ByteArrayBuffer(1024);
            int current = 0;
            while ((current = bis.read()) != -1) {
            	baf.append((byte) current);
            }

            /* Convert the Bytes read to a String. */
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baf.toByteArray());
            fos.flush();
            fos.close();
            Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
        } catch (Exception e) {
        	e.printStackTrace();
        	Log.e(Information.TAG_DBUG, e.getMessage());
        }
	}
	
	public static void setFileName(String filename) {
		mFileName = filename;
	}
	
	public static String getFileName(String extension) {
		return PathManager.combineExtension(mFileName, extension);
	}
    
	@Override
    protected void onPostExecute(String unused) {
		TheNationMain.dismissDownload(mActivity);
    }
    
    @Override
    protected void onProgressUpdate(String... progress) {
        int total = Integer.parseInt(progress[0]);
        TheNationMain.getInstanceDownloadDialog(mActivity).setProgress(total);
    }
}
